package com.xiyang.web.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.Assert;


/**
 * json工具类
 * @author xiyang.ycj
 * @since Sep 10, 2019 17:10:59 PM
 */
public class JsonUtil {


    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        // 忽略多余字段 不会抛出异常
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * json转非泛型
     *
     * @param json
     * @param cls
     * @return
     */
    public static <T> T toObject(String json, Class<T> cls) {
//        if (StringUtils.isBlank(json)) {
//            return null;
//        }
        try {
            return mapper.readValue(json, cls);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 对象转json
     *
     * @param obj
     * @return
     */
    public static  String toJson(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 对象克隆
     *
     * @param source 来源类
     * @param target 目标类
     * @return 目标类
     */
    public static  <T> T clone(Object source, Class<T> target) {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        return toObject(toJson(source), target);
    }
}
